package com.zeedev.flyingsaucer.beers.downloaders;

import android.content.Context;
import android.widget.Toast;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
import com.zeedev.flyingsaucer.beers.activities.storechooser.StoreSpinner;
import com.zeedev.flyingsaucer.modules.StoreModule.interfaces.Store;
import mobi.zeedev.flyingsaucer.common.DataModule.tree.DatabaseTree;
import mobi.zeedev.flyingsaucer.common.WebLinkModule.interfaces.UfoClubClient;
import roboguice.util.Ln;
import roboguice.util.RoboAsyncTask;

/**
 * User: James Johnson
 * Date: Oct 28, 2010
 * Time: 8:54:07 PM
 */

public class StoreDownloader extends RoboAsyncTask {

    @Inject
    @Named("childOfLoginActivity")
    Provider<StoreSpinner> storeSpinnerProvider;

    @Inject
    Provider<Context> contextProvider;

    private final Store stores;

    @Inject
    UfoClubClient beerWebLink;

    @Inject
    public StoreDownloader(Store stores) {
        this.stores = stores;
    }

    @Override
    public Object call() throws Exception {
        DatabaseTree tree = beerWebLink.getStoresTree();
        return tree;
    }

    @Override
    protected void onPreExecute() throws Exception {
        super.onPreExecute();
        storeSpinnerProvider.get().setRefreshing(true);
    }

    @Override
    protected void onException(Exception e) throws RuntimeException {
        super.onException(e);
        Ln.w(e);
        Toast.makeText(contextProvider.get(), "Downloading the stores list failed: " + e.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onFinally() throws RuntimeException {
        super.onFinally();

    }

    @Override
    protected void onSuccess(Object tree) throws Exception {
        super.onSuccess(tree);
        stores.setDatabaseTree((DatabaseTree) tree);
        storeSpinnerProvider.get().setRefreshing(false);


    }


}
